package com.app.babygo;

import java.util.ArrayList;

import com.app.babygo.dbservice.AchievementAdapter;
import com.app.babygo.dbservice.ChildAdapter;
import com.app.babygo.dbservice.UserAdapter;
import com.app.babygo.exceptions.InternalDBException;
import com.app.babygo.exceptions.ObjectNotFoundException;
import com.app.babygo.help.MessageHelper;
import com.app.babygo.help.MongoDBHelper;
import com.app.babygo.help.SqlServerHelper;
import com.app.babygo.obj.AchievementTask;
import com.app.babygo.obj.Child;
import com.app.babygo.obj.User;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ChildChoose extends Activity {

	public final static String SELECTED_CHILD_KEY = "SelectedChild";
	public static String SelectedChildID = "";
	protected static final String TAG = "ChildChoosePage";
	protected ArrayList<Child> ChildList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_child_choose);
		loadChildrenInfo();
		if (ChildList == null) {
			MessageHelper
					.showMsg(this, "Information",
							"You don't have any children. Click add child button to add.");
		} else {
			createChildList();
		}
	}

	// upload to Mongodb and Sqlserver
	public void toServer(View v) {
		MongoDBHelper mongo = new MongoDBHelper();
		mongo.SycServer();

		SqlServerHelper sql = new SqlServerHelper();
		sql.SycServer(getAllAccount(), getAllChildren(), getAllAchievementTaskList());
		
	}

	private User getAllAccount() {
		User currentUser = new User();
		try {
			UserAdapter db = new UserAdapter(this);
			db.open();
			currentUser = db.getAthenticationInfo(Register.currentUserId);
			if(currentUser == null) {
				MessageHelper.showMsg(this, "Sync Error","no user");
			}
			db.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(currentUser.getUsername().equalsIgnoreCase("null")) {
			MessageHelper.showMsg(this, "Sync Error","no user");
			return currentUser;
		} else {
			return currentUser;
		}
		
	}
	private ArrayList<Child> getAllChildren() {
		ArrayList<Child> currentChildren = new ArrayList<Child>();
		try {
			ChildAdapter db = new ChildAdapter(this);
			db.open();
			currentChildren = db.getChildList(Register.currentUserId);
			if(currentChildren.size() == 0) {
				MessageHelper.showMsg(this, "Sync Error","no user");
			}
			db.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return currentChildren;
	}
	
	private ArrayList<AchievementTask> getAllAchievementTaskList() {
		ArrayList<AchievementTask> allAchievement = new ArrayList<AchievementTask>();
		try {
			AchievementAdapter db = new AchievementAdapter(this);
			db.open();
			allAchievement = db.getAchievementTaskList();
			db.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return allAchievement;
	}

	private void loadChildrenInfo() {
		ChildList = new ArrayList<Child>();
		try {
			ChildAdapter dbChild = new ChildAdapter(this);
			dbChild.open();
			ChildList = dbChild.getChildList(Register.currentUserId);
			dbChild.close();
		} catch (InternalDBException e) {
			Log.e(TAG, "Error getting child list: " + e.getMessage());
		} catch (ObjectNotFoundException e) {
			Log.e(TAG, "No Child: " + e.getMessage());
			MessageHelper
					.showMsg(this, "Information",
							"You don't have any children. Click add child button to add.");
		}
	}

	private void createChildList() {
		ListView listView = (ListView) this.findViewById(R.id.child_list);
		listView.setAdapter(new ChildListAdapter(this));
		Button addChildBtn = (Button) this.findViewById(R.id.addnewChild);
		addChildBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				AddChild(v);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.child_choose, menu);
		return true;
	}

	public void AddChild(View v) {
		// releasePage = true;
		Intent intent = new Intent(this, ChildCreation.class);
		startActivity(intent);
		overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
	}

	public final class ViewHolder {
		public ImageView childImg;
		public TextView childName;
		public TextView childInfo;
		public View itemView;
	}

	class ChildListAdapter extends BaseAdapter {
		private LayoutInflater inflater;

		public ChildListAdapter(Context context) {
			super();
			inflater = LayoutInflater.from(context);
		}

		public Object getItem(int position) {
			return ChildList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		@Override
		public int getCount() {
			return ChildList.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			final Child child = ChildList.get(position);
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.child_list_item_layout,
						null);
				holder.childImg = (ImageView) convertView
						.findViewById(R.id.child_img);
				holder.childName = (TextView) convertView
						.findViewById(R.id.child_name);
				holder.childInfo = (TextView) convertView
						.findViewById(R.id.child_info);
				holder.itemView = convertView;
				convertView.setTag(holder); // cache this item view

			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.childName.setText(child.getChildname());
			holder.childInfo.setText(child.getChildinfo());
			Bitmap bitmap = BitmapFactory.decodeFile(child.getChildPicPath());
			holder.childImg.setImageBitmap(bitmap);
			holder.itemView
					.setBackgroundResource(R.drawable.child_list_button_style);

			convertView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(inflater.getContext(),
							TaskList.class);
					intent.putExtra(SELECTED_CHILD_KEY, child);
					startActivity(intent);
					SelectedChildID = child.getCid();
					overridePendingTransition(R.anim.slide_right_in,
							R.anim.slide_left_out);
				}
			});
			convertView.setOnLongClickListener(new View.OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					Intent intent = new Intent(inflater.getContext(),
							ChildInfo.class);
					intent.putExtra(SELECTED_CHILD_KEY, child);
					startActivity(intent);
					overridePendingTransition(R.anim.slide_right_in,
							R.anim.slide_left_out);
					return false;
				}
			});

			return convertView;
		}
	}
}
